package com.hitnet.hitnet;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;
import com.hitnet.hitnet.pic.ActBottomPopWindow;
import com.hitnet.hitnet.pic.FileHandle;
import com.hitnet.hitnet.pic.FormFile;
import com.hitnet.hitnet.pic.NativeImageLoader;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * main view, uploading view and browse website view
 */
public class MainActivity extends Activity {
    private static final int REQ_VIEW_IMAGE = 0x110;
    private static final int RESULT_take_pic = 0x111; //

    //选择图片视图
    private ActBottomPopWindow pWindowPicSelect;

    //拍照图片路径
    private String picPath;

    //hitnet 图片
    private ImageView websiteImage;

    //logout
    private TextView logout;

    LoginManager manager;
    //Volley 的请求队列
    private RequestQueue mQueue ;

    //上传图片
    private ImageView uploadImage;

    //测试时输出的标签
    private static final String TAG = MainActivity.class.getSimpleName();

    //上传时弹出的进度层
    private ProgressDialog progressDialog;

    //sd 卡文件路径
    //public static final String TEMP_PATH = "/sdcard/img_interim/"; //
    public static final String TEMP_PATH = "/sdcard/"; //
    //上传文件总大小
    long totalSize = 0;

    //子线程返回主线程的处理类
    private Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    //hide procgressDialog
                    progressDialog.dismiss();
                    break;
                case 2:
                    progressDialog.dismiss();
                    Intent i = new Intent(MainActivity.this,FaceBookLogin.class);

                    startActivity(i);
                    finish();
                    break;

            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //register facebook sdk
        FacebookSdk.sdkInitialize(getApplicationContext());
        FacebookSdk.setIsDebugEnabled(true);
        setContentView(R.layout.activity_main);

        // initialise request queue
        mQueue = Volley.newRequestQueue(getApplicationContext());

        // set title
        TextView title = (TextView) findViewById(R.id.title);
        title.setText("Home");

        ImageView backImage = (ImageView)findViewById(R.id.comeBack);
        backImage.setVisibility(View.GONE);

        // listen on the uploading event
        uploadImage = (ImageView)findViewById(R.id.upload);
        uploadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // no network connection
                if (getNetworkType() == 0) {

                   ;
                }
                // network is available
                else {

                    Handler handler = new Handler(){
                        public void handleMessage(Message msg) {
                            switch (msg.what) {
                                case 1:
                                    LayoutInflater inflater = (LayoutInflater) getApplicationContext()
                                            .getSystemService(
                                                    Context.LAYOUT_INFLATER_SERVICE);
                                    View pView = inflater.inflate(
                                            R.layout.act_pic_choose_bottom, null);
                                    pWindowPicSelect = new ActBottomPopWindow(
                                            MainActivity.this, pView);
                                    pWindowPicSelect.showAtLocation(
                                            uploadImage,
                                            Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM,
                                            0, 0);
                                    initFilterSelect((ListView) pView
                                            .findViewById(R.id.bottom));
                                    break;
                                case 2:
                                    showAlert("token is expired. Please re-log in");
                                    break;

                            }
                            super.handleMessage(msg);
                        }
                    };
                    // access token is invalid
                    verifyAccessToken(handler);


                }

            }
        });

        //主页图片点击监听事件
        websiteImage = (ImageView) findViewById(R.id.btn);
        websiteImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this,WebAcitivity.class);
                startActivity(i);
            }
        });

        logout = (TextView)findViewById(R.id.logout);
        logout.setVisibility(View.VISIBLE);
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // no network connection
                if (getNetworkType() == 0) {
                    ;
                }
                // network is available
                else {
                    manager = LoginManager.getInstance();
                    manager.logOut();
                    FacebookSdk.clearLoggingBehaviors();
                    progressDialog = ProgressDialog.show(MainActivity.this, "", "logout", true, false);
                    //保存token信息到本地
                    Context ctx = MainActivity.this;
                    SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
                    //存入数据
                    SharedPreferences.Editor editor = sp.edit();

                    String username = sp.getString("username", "");
                    String token = sp.getString("token", "");
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("username", username);
                    params.put("token", token);
                    logoutFromServer("http://54.66.222.127:8000/logout", params);

                    editor.clear();
                    editor.commit();
                }

            }
        });


    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("picPath",picPath);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        picPath = savedInstanceState.getString("picPath");
    }

    public void verifyAccessToken(Handler handler) {


        // get local info
        Context ctx = MainActivity.this;
        SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);

        // get username
        String username = sp.getString("username", "");
        // get token
        String token = sp.getString("token", "");
        Map<String, String> params = new HashMap<String, String>();
        params.put("username", username);
        params.put("token", token);
        String url = "http://54.66.222.127:8000/verify";


        sendToken(url, params, handler);

    }

    public void sendToken(String url, final Map<String, String> params, final Handler handler) {

        StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Log.d("response", response);
                if (response.compareTo("verify") == 0)
                    handler.sendEmptyMessage(1);  //token is valid

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                NetworkResponse networkResponse = error.networkResponse;
                if (networkResponse != null && networkResponse.statusCode == 410) {
                    Log.d("response", networkResponse.toString());
                    handler.sendEmptyMessage(2); // token is expired
                }
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Content-Type", "application/x-www-form-urlencoded");
                return params;
            }
        };
        mQueue.add(sr);
    }

    public static final int NETTYPE_WIFI = 0x01;
    public static final int NETTYPE_CMWAP = 0x02;
    public static final int NETTYPE_CMNET = 0x03;

    /**
     * Name: getNetworkType
     * @return 0：no connection   1：WIFI  2：WAP
     */
    public int getNetworkType() {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        // no network connection
        if (networkInfo == null) {

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Please check your network connection").setTitle("Connection Error")
                    .setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // do nothing
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();

            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            String extraInfo = networkInfo.getExtraInfo();
            if(!StringUtils.isEmpty(extraInfo)){
                if (extraInfo.toLowerCase().equals("cmnet")) {
                    netType = NETTYPE_CMNET;
                } else {
                    netType = NETTYPE_CMWAP;
                }
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = NETTYPE_WIFI;
        }
        return netType;
    }

    /**
     *
     * Name: logoutFromServer
     * Function: Logout current user, return to login page
     */
    public void logoutFromServer(String url, final Map<String, String> params) {

        StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                handler.sendEmptyMessage(2);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                NetworkResponse networkResponse = error.networkResponse;
                if (networkResponse != null && networkResponse.statusCode == HttpStatus.SC_UNAUTHORIZED) {
                    //TODO:
                }
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Content-Type", "application/x-www-form-urlencoded");
                return params;
            }
        };
        mQueue.add(sr);
    }


    /**
     * Name: initFilterSelect
     * Function: Choose
     */
    private void initFilterSelect(ListView view) {
        SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(),
                getPicSelect(), R.layout.item_listview, new String[] {
                "picChoose", "picChooseId" }, new int[] {
                R.id.item_name, R.id.item_id });
        view.setAdapter(adapter);

        //
        view.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                                    long arg3) {
                int picSelect = 0;
                TextView tv_price = (TextView) view
                        .findViewById(R.id.item_name);
                TextView tv_id = (TextView) view.findViewById(R.id.item_id);
                if (tv_price != null) {
                    picSelect = Integer.parseInt(tv_id.getText().toString());
                }

                //take a photo
                if (picSelect == 0) {
                    try {
                        Intent takePictureIntent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        if (takePictureIntent
                                .resolveActivity(getPackageManager()) != null) {

                            File photoFile = null;
                            try {
                                FileHandle createPath = new FileHandle();
                                photoFile = createPath.createImageFile();
                                picPath = photoFile.getAbsolutePath();
                            } catch (IOException ex) {
                                ex.printStackTrace();
                            }

                            if (photoFile != null) {
                                //
                                takePictureIntent.putExtra(
                                        MediaStore.EXTRA_OUTPUT,
                                        Uri.fromFile(photoFile));
                                startActivityForResult(takePictureIntent,
                                        RESULT_take_pic);
                            }
                        }
                    } catch (Exception e) {

                    }
                    pWindowPicSelect.dismiss();

                } else if (picSelect == 1) {
                 //(picSelect == 1) {
                    Intent intent = new Intent(MainActivity.this,
                            com.hitnet.hitnet.pic.MainActivity.class);
                    startActivityForResult(intent, REQ_VIEW_IMAGE);
                    pWindowPicSelect.dismiss();
                } else if (picSelect == 2) {
                    pWindowPicSelect.dismiss();
                }

            }
        });
    }
    /**
     * compress and store images
     * @param path
     * @param fileName
     * @return
     * 2013-12-2
     */
    public File saveMyBitmap(String path, String fileName) {

        //source file
        File sourseFile = new File(path);
        File dir = new File(TEMP_PATH);
        if (!dir.exists()) {
            dir.mkdir();
        }
        File f = new File(TEMP_PATH+fileName+"."+getExtensionName(path));
        Bitmap bitmap = null;
        if (sourseFile.length() / 1024 > 150) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            options.inPurgeable = true;
            options.inInputShareable = true;
            options.inSampleSize = 4;//
            bitmap = BitmapFactory.decodeFile(path, options);
        } else {
            bitmap = BitmapFactory.decodeFile(path);
        }
        try{
            f.createNewFile();
            FileOutputStream fOut = null;
            fOut = new FileOutputStream(f);
            if(sourseFile.length()/1024 >100){ //
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fOut);
            }else{
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            }
            fOut.flush();
            fOut.close();

        }catch(OutOfMemoryError e){
            e.printStackTrace();
            f = null;
        }catch(Exception i){
            i.printStackTrace();
            f = null;
        }finally{
            bitmap = null;

        }
        return f;
    }

    /**
     * compress
     * @param path
     * @return
     */
    public File compressFile(String path){

        //source file
        File sourseFile = new File(path);
        //压缩图片和视频
        if (path.endsWith("mp4")
                ||path.endsWith("avi")){
            //视频没做处理
            return sourseFile;
        }
        Bitmap bitmap = null;
        if (sourseFile.length() / 1024 > 150) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            options.inPurgeable = true;
            options.inInputShareable = true;
            options.inSampleSize = 4;//
            bitmap = BitmapFactory.decodeFile(path, options);
        } else {
            bitmap = BitmapFactory.decodeFile(path);
        }


        try {
            FileOutputStream fOut = null;
            fOut = new FileOutputStream(sourseFile);
            if(sourseFile.length()/1024 > 100){ //
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fOut);
            }else{
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            }
            fOut.flush();
            fOut.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sourseFile;
    }

    /**
     * get extension
     * @param filename
     * @return
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }


    /**
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RESULT_take_pic) {
            File image = new File(picPath);
            if (image.length()>0){
                NativeImageLoader.mSelectList.add(picPath);
            }
        }

        if (NativeImageLoader.mSelectList.size() > 0) {
            progressDialog = ProgressDialog.show(MainActivity.this, "", "uploading", true, false);

            //upload a file asynchronously
            new UploadFileToServer().execute();
        }


//

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 选择菜单标题
     *
     * @return 2014-8-19
     */
    private List<Map<String, Object>> getPicSelect() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        Map<String, Object> map = new HashMap<String, Object>();


        map.put("picChoose", "take a photo");
        map.put("picChooseId", "0");
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("picChoose", "Choose Existing");

        map.put("picChooseId", "1");
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("picChoose", "Cancel");
        map.put("picChooseId", "2");
        list.add(map);

        return list;
    }



    /**
     * Uploading the file to server
     * */
    private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            //进度更新
        }

        @Override
        protected String doInBackground(Void... params) {
            return uploadFile();
        }

        @SuppressWarnings("deprecation")
        private String uploadFile() {
            String responseString = null;

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);

            try {
                AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                        new AndroidMultiPartEntity.ProgressListener() {

                            @Override
                            public void transferred(long num) {
                                publishProgress((int) ((num / (float) totalSize) * 100));
                            }
                        });

                FormFile files[] = new FormFile[NativeImageLoader.mSelectList.size()];

                // add files
                for(String path : NativeImageLoader.mSelectList){
                    File file = compressFile(path);
                    entity.addPart("upload", new FileBody(file));
                }

                // add header

                totalSize = entity.getContentLength();
                httppost.setEntity(entity);

                // Making server call
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity r_entity = response.getEntity();

                int statusCode = response.getStatusLine().getStatusCode();

                //
                if (statusCode == 200) {
                    responseString = EntityUtils.toString(r_entity);

                } else {
                    responseString = EntityUtils.toString(r_entity);
                }
                // remove all images from the loader
                NativeImageLoader.mSelectList.removeAll(NativeImageLoader.mSelectList);

                handler.sendEmptyMessage(1);

            } catch (ClientProtocolException e) {
                responseString = e.toString();
            } catch (IOException e) {
                responseString = e.toString();
            }

            return responseString;

        }

        @Override
        protected void onPostExecute(String result) {

            Log.e(TAG, "Response from server: " + result);
            showAlert(result);
            super.onPostExecute(result);
        }
    }

    /**
     * Method to show alert dialog
     **/
    private void showAlert(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message).setTitle("Response from Server")
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // do nothing
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
}
